package com.kaede.hayate.security.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.kaede.hayate.modules.sys.entity.*;
import com.kaede.hayate.modules.sys.service.*;
import com.kaede.hayate.security.entity.RestGrantedAuthority;
import com.kaede.hayate.security.entity.RestRole;
import com.kaede.hayate.security.entity.RestUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service("userDetailsService")
public class RestUserDetailsService implements UserDetailsService {

    private static final String TAG = "UserDetailsServiceImpl";

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IAuthorityService authorityService;

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IRoleAuthorityService roleAuthorityService;

    @Override
    /*@Cacheable(TAG)*/
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return getRestUserDetailByUsername(username);
    }

    private RestUserDetails getRestUserDetailByUsername(String username){

        User user = userService.selectOne(new EntityWrapper<User>().eq("username", username));
        if(user == null || StringUtils.isEmpty(user.getUsername())){
            throw new UsernameNotFoundException("用户名或密码错误");
        }else {
            //userDetails的roleList
            List<RestRole> restRoleList = new ArrayList<>();
            //userDetails的authorityList
            List<RestGrantedAuthority> restGrantedAuthorityList = new ArrayList<>();

            //查询该用户对应的角色
            List<UserRole> userRoleList = userRoleService.selectList(new EntityWrapper<UserRole>().eq("user_id", user.getId()));
            if(userRoleList != null && !userRoleList.isEmpty()){
                List<Long> roleIdList = userRoleList.stream().map(userRole -> userRole.getRoleId()).collect(Collectors.toList());
                List<Role> roleList = roleService.selectBatchIds(roleIdList);
                if(roleList != null && !roleList.isEmpty()){
                    roleList.forEach(role -> restRoleList.add(new RestRole(role.getId(), role.getName(), role.getEnname(), role.getSysFlag())));
                }

                //查询每个角色对应的权限
                for(Long roleId : roleIdList){
                    List<RoleAuthority> roleAuthorityList = roleAuthorityService.selectList(new EntityWrapper<RoleAuthority>().eq("role_id", roleId));
                    if(roleAuthorityList != null && !roleAuthorityList.isEmpty()){
                        List<Long> authorityIdList = roleAuthorityList.stream().map(roleAuthority -> roleAuthority.getAuthorityId()).collect(Collectors.toList());
                        List<Authority> authorityList = authorityService.selectBatchIds(authorityIdList);
                        if(authorityList != null && !authorityList.isEmpty()){
                            authorityList.forEach(authority -> restGrantedAuthorityList.add(new RestGrantedAuthority(authority.getId(), authority.getUrl(), authority.getMethod())));
                        }
                    }
                }
            }
            return new RestUserDetails(user.getId().toString(), user.getName(), user.getUsername(), user.getPassword(),
                    user.getTokenSecret(), restRoleList, restGrantedAuthorityList);
        }
    }
}
